var db = require('../../sqldb');
var User = db.User;
var moment = require('moment');
var auth = require('../../auth/auth.service');
var common = new require('../global/common.service')('User');

// 用户登录验证
exports.passwordLogin = function(body) {
    return db.sequelize.transaction(function(t) {
        // 搜索请求用户
        return User.findOne({
            where: {
                UserId: body.UserId,
                PassWord: body.PassWord,
                Role: body.Role                         // 用role作为权限判断
            }
        }, {
            transaction: t
        }).then(function(user) {
            // 如果用户不存在
            if (!user) {
                throw new Error('用户不存在，请先注册!');
            }
            // 如果密码不正确
            var isValid = body.PassWord == user.PassWord;
            if (!isValid) {
                throw new Error('用户名或密码错误!');
            }
            // 用户存在，记录登录信息
            var tokenMsg = {
                UserId: user.UserId
            };
            var token = auth.signToken(tokenMsg);
            var LastLoginTime = (new Date(moment().format('YYYY-MM-DD HH:mm:ss'))).getTime();
            return user.update({
                LastLoginTime: LastLoginTime
            }, {
                transaction: t
            }).then(function(result) {
                return {
                    token: token,
                    user: {
                        UserId: result.UserId,
                        UserName: result.UserName,
                        PassWord: result.PassWord,
                        Role: result.Role,
                        updatedAt: result.updatedAt
                    }
                }
            });
        });
    });
}
// 新增用户
exports.register = function(body) {
    return db.sequelize.transaction(function(t) {
        body.LastLoginTime = (new Date(moment().format('YYYY-MM-DD HH:mm:ss'))).getTime();
        return User.create({
            UserId: body.UserId,
            PassWord: body.PassWord,
            UserName: body.UserName,
            Role: body.Role,
            LastLoginTime: body.LastLoginTime
        }, {
            transaction: t
        }).then(function(result) {
            return result;
        });
    });
}
// 用户列表
exports.list = function(body) {
    return db.sequelize.transaction(function(t) {
        return common.list(body,t);
    })
}
// 更新
exports.edit = function(body) {
    return db.sequelize.transaction(function(t) {
        return common.edit(body,t);
    })
}
// 删除
exports.del = function(body) {
    return db.sequelize.transaction(function(t) {
        return common.del(body,t);
    })
}